package com.example.mybatisplus.web.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Assert;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.stereotype.Controller;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.example.mybatisplus.common.JsonResponse;
import com.example.mybatisplus.service.StampService;
import com.example.mybatisplus.model.domain.Stamp;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileInputStream;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
import java.util.Base64.Encoder;
import java.util.Base64.Decoder;


/**
 *
 *  前端控制器
 *
 *
 * @author lxp
 * @since 2022-02-28
 * @version v1.0
 */
@Controller
@RequestMapping("/stamp")
public class StampController {

    private final Logger logger = LoggerFactory.getLogger( StampController.class );

    @Autowired
    private StampService stampService;

    /**
    * 描述：根据Id 查询
    *
    */
    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    @ResponseBody
    public JsonResponse getById(@PathVariable("id") Long id)throws Exception {
        Stamp  stamp =  stampService.getById(id);
        return JsonResponse.success(stamp);
    }

    /**
    * 描述：根据Id删除
    *
    */
    @RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
    @ResponseBody
    public JsonResponse deleteById(@PathVariable("id") Long id) throws Exception {
        stampService.removeById(id);
        return JsonResponse.success(null);
    }


    /**
    * 描述：根据Id 更新
    *
    */
    @RequestMapping(value = "/{id}", method = RequestMethod.PUT)
    @ResponseBody
    public JsonResponse updateStamp(@PathVariable("id") Long  id,Stamp  stamp) throws Exception {
        stamp.setId(id);
        stampService.updateById(stamp);
        return JsonResponse.success(null);
    }


    /**
    * 描述:创建Stamp
    *
    */
    @RequestMapping(value = "", method = RequestMethod.POST)
    @ResponseBody
    public JsonResponse create(@RequestBody Stamp  stamp) throws Exception {
        stampService.save(stamp);
        return JsonResponse.success(null);
    }

    @RequestMapping(value = "/addStamp", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> uploadFile(@RequestParam(value = "file") MultipartFile[] file, HttpServletRequest request) {
        {
            Assert.notNull(file, "上传文件不能为空");
            String filepath = System.getProperty("user.dir") + "/src/main/resources/static/Stamp/uploadFile/";//上传到这个文件夹
            //System.out.println("保存路径:"+ filepath);
            Map map = new HashMap<String, Object>();
            int len = file.length;
            for (int i = 0; i < len; i++) {
                System.out.println(i+"---------------------------test-------------------------");
                String filename = System.currentTimeMillis() + file[i].getOriginalFilename();
                System.out.println("文件名字测試："+filename);
                File filetest = new File(filepath);
                System.out.println("文件路徑測試："+filetest.getPath());
                if (!filetest.exists()) {
                    filetest.mkdirs();
                }
                String savepath = filepath + '\\' + filename;
                savepath = savepath.replace("\\", "/");
                String savename = savepath.substring(savepath.lastIndexOf("/") + 1);
                String Faid = request.getParameter("id");
                long Fid = Long.parseLong(Faid);
                try {
                    //保存文件到服务器
                    file[i].transferTo(new File(savepath));
                    //保存到数据库
                    Stamp stamp = new Stamp();
                    stamp.setImage(savename);
                    stamp.setId(Fid);
                    QueryWrapper<Stamp> wrapper = new QueryWrapper<>();
                    wrapper.eq("id", Fid);
                    Stamp list1 = stampService.getOne(wrapper);
                    //直接插入新数据
                    stampService.saveOrUpdate(stamp);

                    //返回json
                    map.put("msg", "ok");
                    map.put("code", 200);
                    //   加不加这个都行
//            map.put("data",new HashMap<String,Object>(){
//                {
//                    put("src",savepath);
//                }
//            });

                } catch (Exception e) {
                    map.put("msg", "error");
                    map.put("code", 0);
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    @RequestMapping(value = "/getStamp/{id}", method = RequestMethod.GET)
    @ResponseBody
    public JsonResponse encodeBase64File(@PathVariable("id") Long id) throws Exception {
        Stamp  picture =  stampService.getById(id);
        String filename = picture.getImage();
        String filepath =  System.getProperty("user.dir") +
                "/src/main/resources/static/Stamp/uploadFile/" + filename;//改了路径
        filepath = filepath.replace("\\", "/");
        System.out.println(filepath);
        File file = new File(filepath);
        FileInputStream inputFile = new FileInputStream(file);
        byte[] buffer = new byte[(int)file.length()];
        inputFile.read(buffer);
        inputFile.close();
//        Encoder encoder = Base64.getEncoder();
//        Decoder decoder = Base64.getDecoder();
        return JsonResponse.success( Base64.getEncoder().encode(buffer),filename);
    }
}

